<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" formType="show" :isSubmitBtn="false" />
    <BreakSpace label="审核记录" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FilterTable
      ref="table"
      columnsRef="rescueEditDialog"
      height="200"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
    >
    </FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <!--  <AjaxButton type="primary" :click="saveClick">保存</AjaxButton> -->
      <AjaxButton type="primary" :click="submitClick">撤 销</AjaxButton>
      <el-button @click="closeDialog">关 闭</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { phone } from '@/utils/validate';
import dictCode from '@/utils/dictCode';
import { region } from '@/api/cms-common/region'; //行政区域
import moment from 'moment';
import { saveRescue, getResultList, assessorStatus } from '@/api/repair/repairBusiness/rescueService/index';

export default {
  name: 'rescueEditDialog',
  props: {
    row: {
      type: Object,
      default: {}
    },
    type: {
      type: String
    }
  },
  mixins: [dictionary, region],
  data() {
    return {
      formList: this.createFormList(),
      regionList: [],
      fetchParams: { xhrAbort: false, rescueNo: this.row.rescueNo, ownerCode: this.row.ownerCode },
      fetchApi: getResultList,
      columns: this.createTableColumns()
    };
  },
  computed: {
    totalFee() {
      //总金额=过桥过路费+其他费用+人员补助+交通补助+住宿补助+拖车费用；
      let roadFee = this.formList.find(x => x.fieldName === 'roadFee').initialValue || 0;
      let otherFee = this.formList.find(x => x.fieldName === 'otherFee').initialValue || 0;
      let personFee = this.formList.find(x => x.fieldName === 'personFee').initialValue || 0;
      let trafficFee = this.formList.find(x => x.fieldName === 'trafficFee').initialValue || 0;
      let stayFee = this.formList.find(x => x.fieldName === 'stayFee').initialValue || 0;
      let trailerFee = this.formList.find(x => x.fieldName === 'trailerFee').initialValue || 0;
      let totalFee = Number(roadFee) + Number(otherFee) + Number(personFee) + Number(trafficFee) + Number(stayFee) + Number(trailerFee);
      this.formList.find(x => x.fieldName === 'totalFee').initialValue = totalFee;
      return totalFee;
    }
  },
  watch: {
    totalFee(newValue, oldValue) {
      console.log(newValue, 'hexj001');
    }
  },
  mounted() {
    this.initProvince();
    if (this.type === 'add') {
    } else {
      // 回显省市县
      if (this.row.outProvince) {
        this.initCity('out', Number(this.row.outProvince));
      }
      if (this.row.outCity) {
        this.initDistrict('out', Number(this.row.outCity));
      }
      if (this.row.rescueProvince) {
        this.initCity('rescue', Number(this.row.rescueProvince));
      }
      if (this.row.rescueCity) {
        this.initDistrict('rescue', Number(this.row.rescueCity));
      }
      this.formList.forEach(x => {
        if (
          x.fieldName === 'rescueObject' ||
          x.fieldName === 'vehicle' ||
          x.fieldName === 'outProvince' ||
          x.fieldName === 'outCity' ||
          x.fieldName === 'outArea' ||
          x.fieldName === 'rescueProvince' ||
          x.fieldName === 'rescueCity' ||
          x.fieldName === 'rescueArea'
        ) {
          x.initialValue = Number(this.row[x.fieldName]);
        } else {
          x.initialValue = this.row[x.fieldName];
        }
        x.disabled = true;
        x.rules = [];
        x.placeholder = '';
      });
      // 处理车型翻译
      this.formList.find(x => x.fieldName === 'model').itemList = [{ text: this.row['modelName'] || '', value: this.row['model'] || '' }];
      // if (this.type === 'show') {
      //   this.formList.forEach(x => {
      //     x.disabled = true;
      //     x.rules = [];
      //     x.placeholder = '';
      //   });
      // }
      // if (this.row.fileAddr && this.row.fileName){
      //   let fileObj = {
      //     name: this.row.fileName,
      //     url: this.row.fileAddr
      //   };
      //   this.formList.find(x => x.fieldName === 'url').initialValue = [fileObj];
      //   console.log(fileObj)
      // }
    }
  },
  methods: {
    vehicleInfo(row) {
      this.actions.visible = false;
      this.formList.find(x => x.fieldName === 'license').initialValue = row['license'];
      this.formList.find(x => x.fieldName === 'vin').initialValue = row['vin'];
      this.formList.find(x => x.fieldName === 'model').initialValue = row['model'];
      this.formList.find(x => x.fieldName === 'engineNo').initialValue = row['engineNo'];
      this.formList.find(x => x.fieldName === 'guaranteeBegDate').initialValue = row['guaranteeBegDate'];
      this.formList.find(x => x.fieldName === 'mileage').initialValue = row['mileage'];
      this.formList.find(x => x.fieldName === 'ownerName').initialValue = row['ownerName'];
      this.formList.find(x => x.fieldName === 'ownerMobile').initialValue = row['ownerMobile'];
    },
    createFormList() {
      const province = this.createRegionsList();
      const citys = this.createcityList();
      const area = this.createcityList();
      return [
        {
          type: 'BREAK_SPACE',
          label: '车辆信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: 'rescueId',
          fieldName: 'rescueId',
          hidden: true
        },
        {
          type: 'INPUT',
          label: '救援单编号',
          fieldName: 'serviceNo',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'ownerShortName',
          placeholder: '请输入...',
          disabled: true
        },

        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.actions.visible = true;
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请输入...',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '发动机号/电机号',
          fieldName: 'engineNo',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '当前里程数',
          fieldName: 'mileage',
          initialValue: 0,
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          // disabled: true,
          precision: 2
        },
        {
          type: 'DATE',
          label: '保修开始日期',
          fieldName: 'guaranteeBegDate',
          placeholder: '请选择...',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          // initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'ownerMobile',
          rules: [{ required: true, message: '请输入正确的手机号', trigger: 'change', validator: phone }]
        },

        {
          type: 'BREAK_SPACE',
          label: '救援信息',
          style: {}
        },

        {
          type: 'INPUT',
          label: '救援单号',
          fieldName: 'rescueNo',
          placeholder: '请输入...',
          disabled: true
        },

        {
          type: 'INPUT',
          label: '报修人',
          fieldName: 'repairUser',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '报修人电话',
          fieldName: 'repairMobile',
          rules: [{ required: true, message: '请输入正确的手机号', trigger: 'blur', validator: phone }]
        },

        {
          type: 'SELECT',
          label: '救援方',
          fieldName: 'rescueObject',
          placeholder: '请输入...',
          itemList: this.createDictList('9996'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '救援方式',
          fieldName: 'rescueType',
          placeholder: '请输入...',
          itemList: this.createDictList('9997'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '申请日期',
          fieldName: 'applyDate',
          placeholder: '请选择...',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
        },
        {
          type: 'TEXT_AREA',
          label: '外出原因',
          fieldName: 'outResult',
          selfCols: 3,
          maxlength: 300
        },
        {
          type: 'SELECT',
          label: '出发省份',
          fieldName: 'outProvince',
          placeholder: '请输入...',
          itemList: this.createRegionList(),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          change: val => {
            if (val) {
              this.initCity('out', val);
            } else {
              this.formList.find(x => x.fieldName === 'outCity').initialValue = undefined;
              this.formList.find(x => x.fieldName === 'outArea').initialValue = undefined;
            }
          }
        },
        {
          type: 'SELECT',
          label: '出发城市',
          fieldName: 'outCity',
          placeholder: '请输入...',
          itemList: [],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          change: val => {
            if (val) {
              this.initDistrict('out', val);
            } else {
              this.formList.find(x => x.fieldName === 'outArea').initialValue = undefined;
            }
          }
        },
        {
          type: 'SELECT',
          label: '出发县区',
          fieldName: 'outArea',
          placeholder: '请输入...',
          itemList: [],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '出发地址',
          fieldName: 'outAddr',
          placeholder: '请输入...',
          selfCols: 3,
          maxlength: 100,
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '故障地省份',
          fieldName: 'rescueProvince',
          placeholder: '请输入...',
          itemList: this.createRegionList(),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          change: val => {
            if (val) {
              this.initCity('rescue', val);
            } else {
              this.formList.find(x => x.fieldName === 'rescueCity').initialValue = undefined;
              this.formList.find(x => x.fieldName === 'rescueArea').initialValue = undefined;
            }
          }
        },
        {
          type: 'SELECT',
          label: '故障地城市',
          fieldName: 'rescueCity',
          placeholder: '请输入...',
          itemList: [],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          change: val => {
            if (val) {
              this.initDistrict('rescue', val);
            } else {
              this.formList.find(x => x.fieldName === 'rescueArea').initialValue = undefined;
            }
          }
        },
        {
          type: 'SELECT',
          label: '故障地县区',
          fieldName: 'rescueArea',
          placeholder: '请输入...',
          itemList: [],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '故障发生地址',
          fieldName: 'rescueAddr',
          placeholder: '请输入...',
          selfCols: 3,
          maxlength: 100,
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '外出里程',
          fieldName: 'outMileage',
          placeholder: '请输入...',
          style: { width: `calc(100% - 70px)` },
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          descOptions: {
            content: 'KM(里程)'
          },
          precision: 2
        },
        {
          type: 'SELECT',
          label: '交通工具',
          fieldName: 'vehicle',
          placeholder: '请输入...',
          itemList: this.createDictList('9998'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '服务车牌号',
          fieldName: 'serviceLicense',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT_NUMBER',
          label: '过桥过路费',
          fieldName: 'roadFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '其他费用',
          fieldName: 'otherFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '外出人数',
          fieldName: 'outPerson',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          precision: 0
        },
        {
          type: 'DATE',
          label: '开始日期',
          fieldName: 'begDate',
          placeholder: '请选择...',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '结束日期',
          fieldName: 'endDate',
          placeholder: '请选择...',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          // initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '人员补助',
          fieldName: 'personFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '交通补助',
          fieldName: 'trafficFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '住宿补助',
          fieldName: 'stayFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '拖车费用',
          fieldName: 'trailerFee',
          placeholder: '请输入...',
          initialValue: 0,
          precision: 2
        },
        {
          // 总金额=过桥过路费+其他费用+人员补助+交通补助+住宿补助+拖车费用；
          type: 'INPUT_NUMBER',
          label: '总金额',
          fieldName: 'totalFee', // 后台不存，前台需要计算
          placeholder: '请输入...',
          disabled: true,
          // initialValue: this.totalFee,
          precision: 2
        },
        {
          type: 'TEXT_AREA',
          label: '费用备注',
          fieldName: 'feeRemarks',
          selfCols: 3,
          maxlength: 300
        },
        {
          type: 'TEXT_AREA',
          label: '处理结果',
          fieldName: 'handleResult',
          selfCols: 3,
          maxlength: 300
        },
        {
          type: 'TEXT_AREA',
          label: '备注说明',
          fieldName: 'remarks',
          selfCols: 3,
          maxlength: 300
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'url',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            fileTypes: ['jpg', 'png', 'pdf', 'rar'],
            max: 1024 * 100,
            limit: 1
          },
          initialValue: [],
          disabled: false,
          selfCols: 1
        }
      ];
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作人',
          dataIndex: 'handlerName',
          sorter: true
        },

        {
          title: '操作时间',
          dataIndex: 'createdAt',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        },
        {
          title: '操作后状态',
          dataIndex: 'status',
          sorter: true,
          dictItems: this.createDictList('9995')
        },
        {
          title: '审核意见',
          dataIndex: 'checkResult',
          width: 150,
          sorter: true
        }
      ];
    },
    async saveDialog(type) {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      let params = { ...data };
      params.status = type;
      params.type = type;
      params.rescueId = this.formList.find(x => x.fieldName === 'rescueId').initialValue;
      let res = await assessorStatus(params);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '保存成功！' });
        if (type === '99951001') {
          this.formList.find(x => x.fieldName === 'rescueNo').initialValue = res.data.rescueNo;
          this.formList.find(x => x.fieldName === 'serviceNo').initialValue = res.data.serviceNo;
          this.formList.find(x => x.fieldName === 'rescueId').initialValue = res.data.rescueId;
        } else {
          // 提交成功关闭dialog
          this.closeDialog();
        }
      }
    },
    // 撤销
    submitClick() {
      this.saveDialog('99951003');
    },
    // // 保存
    // saveClick() {
    //   this.saveDialog('99951001');
    // },

    closeDialog() {
      this.$emit('close', false);
    },

    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.formList.find(item => item.fieldName === 'outProvince').itemList = pl;
      this.formList.find(item => item.fieldName === 'rescueProvince').itemList = pl;
    },
    //初始化所在市数据
    async initCity(flag, provinceId) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      console.log(rd, 'rd:::');
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.formList.find(item => item.fieldName === 'outCity');
      if (flag === 'rescue') {
        // 救援地址
        city = this.formList.find(item => item.fieldName === 'rescueCity');
      }
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.formList.find(item => item.fieldName === 'outArea');
      if (flag === 'rescue') {
        // 救援地址
        district = this.formList.find(item => item.fieldName === 'rescueArea');
      }
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在区数据
    async initDistrict(flag, cityId) {
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }
      let cl = this.district(cityId);
      //初始化区县，清除原值
      let district = this.formList.find(item => item.fieldName === 'outArea');
      if (flag === 'rescue') {
        // 救援地址
        district = this.formList.find(item => item.fieldName === 'rescueArea');
      }
      district.itemList = cl;
      district.initialValue = '';
    }
    // async getProvine() {
    //   const allRegion = await getRegion();
    //   this.regionList = allRegion.data.map(x => ({ value: x.regionId, text: x.regionName }));
    //   console.log('this.regionList', this.regionList);
    //   console.log('allRegion', allRegion);
    // }
  }
};
</script>
